package com.lu.security.cipher;

import java.security.GeneralSecurityException;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import com.lu.security.key.DefaultKey;
import com.lu.security.tools.HexTools;

/**
 * author: luqihua
 * date:2019-07-10
 * description: DES加解密工具类
 * 加密模式是 ECB
 * 数据块分组 PKCS5Padding
 **/
public class DESCipher {
    private static final String TAG = "DESCipher";
    private static final String DES_MODEL = "DES/ECB/PKCS5Padding";

    private final Key mSecurityKeySpec;

    public DESCipher(String keyText) {
        this(keyText.getBytes());
    }

    public DESCipher(byte[] keyBytes) {
        this.mSecurityKeySpec = new SecretKeySpec(keyBytes, "DES");
    }

    public static DESCipher getDefault() {
        return new DESCipher(DefaultKey.nDefaultKey());
    }


    public String encryptBase64(String data) throws GeneralSecurityException {
        Cipher cipher = Cipher.getInstance(DES_MODEL);
        cipher.init(Cipher.ENCRYPT_MODE, mSecurityKeySpec);//加密数据
        return HexTools.encodeToBase64(cipher.doFinal(data.getBytes()));
    }


    public String decryptBase64(String encrypt) throws GeneralSecurityException {

        Cipher cipher = Cipher.getInstance(DES_MODEL);
        cipher.init(Cipher.DECRYPT_MODE, mSecurityKeySpec);//解密数据
        byte[] source = HexTools.decodeFromBase64(encrypt);
        return new String(cipher.doFinal(source));
    }


    public byte[] encrypt(byte[] data) throws GeneralSecurityException {
        Cipher cipher = Cipher.getInstance(DES_MODEL);
        cipher.init(Cipher.ENCRYPT_MODE, mSecurityKeySpec);//加密数据
        return cipher.doFinal(data);
    }

    public byte[] decrypt(byte[] encryptData) throws GeneralSecurityException {
        Cipher cipher = Cipher.getInstance(DES_MODEL);
        cipher.init(Cipher.DECRYPT_MODE, mSecurityKeySpec);//解密数据
        return cipher.doFinal(encryptData);
    }


    public boolean verifyDES(String src, String encryptBase64) throws GeneralSecurityException {
        String decrypt = decryptBase64(encryptBase64);
        if (decrypt != null) {
            return decrypt.equals(src);
        }
        return false;
    }
}
